﻿using MapleLeaf.IdentityServer.Models;
using Microsoft.AspNetCore.Hosting;
using Microsoft.AspNetCore.Mvc;
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using Newtonsoft.Json;
using IdentityServer4.EntityFramework.DbContexts;
using Microsoft.EntityFrameworkCore;
using IdentityServer4.EntityFramework.Mappers;
using IdentityServer4.Models;
using IdentityServer4;
namespace MapleLeaf.IdentityServer.Controllers {
    [Route("api/[controller]/[action]")]
    [ApiController]
    public class SystemController : BaseController {
        private readonly IWebHostEnvironment _webHostEnvironment;
        private readonly ConfigurationDbContext _context;
        private readonly MapleLeafDbContext _mlContext;


        public SystemController(IWebHostEnvironment hostEnvironment, ConfigurationDbContext dbContext, MapleLeafDbContext mapleLeafDbContext) {
            _webHostEnvironment = hostEnvironment;
            _context = dbContext;
            _mlContext = mapleLeafDbContext;
        }

        /// <summary>
        /// /
        /// </summary>
        /// <returns></returns>
        [HttpGet]
        public IActionResult GetInitData() {

            //获取存储静态资源的wwwroot所在的根目录
            string webRootPath = _webHostEnvironment.WebRootPath;
            var fullPath = Path.Combine(webRootPath, @"api\init.json");
            string content = System.IO.File.ReadAllText(fullPath, Encoding.UTF8);

            var data = JsonConvert.DeserializeObject<InitDataModel>(content);
            return Success(data);

        }
        public async Task<IActionResult> GetClientsAsync() {
            var clients = await _context.Clients.ToListAsync();
            List<ClientViewModel> list = new();
            foreach (var client in clients) {
                var m = new ClientViewModel {
                    Id = client.Id,
                    ClientId = client.ClientId,
                    ClientName = client.ClientName,
                    ClientType = "",
                    AllowedGrantTypes = string.Join(";", client.AllowedGrantTypes ?? new List<IdentityServer4.EntityFramework.Entities.ClientGrantType>()),
                    LoginRedirectUris = string.Join(";", client.RedirectUris ?? new List<IdentityServer4.EntityFramework.Entities.ClientRedirectUri>()),
                    LogoutRedirectUris = string.Join(";", client.PostLogoutRedirectUris ?? new List<IdentityServer4.EntityFramework.Entities.ClientPostLogoutRedirectUri>()),
                    AllowedScopes = string.Join(";", client.AllowedScopes ?? new List<IdentityServer4.EntityFramework.Entities.ClientScope>()),
                    AllowedCorsOrigins = string.Join(";", client.AllowedCorsOrigins ?? new List<IdentityServer4.EntityFramework.Entities.ClientCorsOrigin>()),
                    AllowAccessTokensViaBrowser = client.AllowAccessTokensViaBrowser,
                    AccessTokenLifetime = client.AccessTokenLifetime,
                    Description = client.Description,
                  
                };
                list.Add(m);
            }
            return Success(list);
        }


        public IActionResult DeleteClient(string ClientName) {
            var clientItem = _context.Clients.FirstOrDefault(x => x.ClientName == ClientName);
            _context.Clients.Remove(clientItem);
            _context.SaveChanges();
            return Success("删除成功");
        }

        /// <summary>
        /// 注册
        /// </summary>
        /// <param name="client"></param>
        /// <returns></returns>
        public IActionResult RegisterClient(ClientViewModel model) {
            _context.Database.Migrate();
            var clientItem = _context.Clients.FirstOrDefault(x => x.ClientName == model.ClientName);
            if (clientItem == null) {
                List<string> allowedScops = new() {
                    IdentityServerConstants.StandardScopes.OpenId,
                    IdentityServerConstants.StandardScopes.Profile,
                };
                if (!string.IsNullOrWhiteSpace(model.AllowedScopes)) {
                    string scopes = model.AllowedScopes.Replace("；", ";").Trim(';');
                    foreach (var ascope in scopes.Split(";")) {
                        if (string.IsNullOrWhiteSpace(ascope)) {
                            continue;
                        }
                        allowedScops.Add(ascope);
                    }
                }
                Client client = new() {
                    ClientId = model.ClientName,
                    ClientName = model.ClientName,
                    AllowedGrantTypes = GrantTypes.Implicit,
                    AllowAccessTokensViaBrowser = true,
                    RedirectUris = string.IsNullOrWhiteSpace(model.LoginRedirectUris) ? new List<string>() : model.LoginRedirectUris.Split(";"),
                    AllowedCorsOrigins = string.IsNullOrWhiteSpace(model.AllowedCorsOrigins) ? new List<string>() : model.AllowedCorsOrigins.Split(";"),
                    AccessTokenLifetime = 3600,
                    PostLogoutRedirectUris = string.IsNullOrWhiteSpace(model.LogoutRedirectUris) ? new List<string>() : model.LogoutRedirectUris.Split(";"),
                    AllowedScopes = allowedScops
                };
                _context.Clients.Add(client.ToEntity());
                _context.SaveChanges();
            } else {
                return Fail("客户端已存在!");
            }

            if (!_context.IdentityResources.Any()) {
                Console.WriteLine("IdentityResources being populated");
                foreach (var resource in Config.GetIdentityResources().ToList()) {
                    _context.IdentityResources.Add(resource.ToEntity());
                }
                _context.SaveChanges();
            } else {
                Console.WriteLine("IdentityResources already populated");
            }

            if (!_context.ApiResources.Any()) {
                Console.WriteLine("ApiResources being populated");
                foreach (var resource in Config.GetApiResources().ToList()) {
                    _context.ApiResources.Add(resource.ToEntity());
                }
                _context.SaveChanges();
            } else {
                Console.WriteLine("ApiResources already populated");
            }

            if (!_context.ApiScopes.Any()) {
                Console.WriteLine("ApiScopes being populated");
                foreach (var resource in Config.GetApiScopes().ToList()) {
                    _context.ApiScopes.Add(resource.ToEntity());
                }
                _context.SaveChanges();
            } else {
                Console.WriteLine("ApiScopes already populated");
            }
            return Success("注册成功!");

        }

    }
}

